/*
    Copyright Nicolas Ronvel 2007
	gulix33xp@yahoo.fr

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Drawing;

using SdlDotNet.Core;

using BlindShark.GameElements;

using Gulix.Audio;

namespace BlindShark.GameStates
{
	public class GS_ChangeTrack : GameState
	{
		bool _bInit; // No need to change track if true
		
		public GS_ChangeTrack(bool init)
		{
			_bInit = init;
		}
		
		public void Draw()
		{

		}
		
		
		public void CleanUp()
		{
			Events.Remove();
		}
		
		public void HandleEvents()
		{
			while (Events.Poll());
		}
		
		public void Update()
		{
			while ((GameManager.CurrentTrack!=null) && (!System.IO.File.Exists(GameManager.CurrentTrack.Filename)))
				GameManager.ChangeTrack();
			
			if (GameManager.CurrentTrack==null)
				GameStateManager.ChangeState(new GS_EndGame());
			else
			{
				AudioEngine.PlayMusic(GameManager.CurrentTrack.Filename, true);
				// According to the configuration, we set the starting point of the track
				if (GameManager.RandomStart)
				{
					double totalTime = AudioEngine.MusicTotalTime.TotalMilliseconds;
					double limit = (GameManager.RndStartLimitMax-GameManager.RndStartLimitMin) * totalTime / 100.0;
					
					Random rnd = new Random(Convert.ToInt32(ClockManager.GetTime()));
					
					AudioEngine.MusicElapsedTime
						= TimeSpan.FromMilliseconds((totalTime * GameManager.RndStartLimitMin/ 100.0)
						                            + rnd.NextDouble()*limit);
				}
				
				GameStateManager.ChangeState(new GS_CheckPlayers());
			}
		}
		
		public void Init()
		{
			for (int i=0; i<PlayerManager.Count; i++)
				PlayerManager.SetState(i, PlayerState.inGame);
			// Loading the new track
			if (!_bInit)
				GameManager.ChangeTrack();
			GameManager.NewSong = true;
			
			// Pausing the music if it's not aready done, and if the last track wasn't the last one
			if (AudioEngine.MusicPlaying && (GameManager.CurrentTrack!=null))
				AudioEngine.PauseMusic();
		}
	}
}
